import router from '@/router'
// 缓存navTabs
const persistNavTabs = (navTabs) => {
  sessionStorage.setItem('navTabs', JSON.stringify(navTabs))
}
export default {
  namespaced: true,
  state: {
    // 侧边栏折叠状态
    navCollapse: false,
    // 定义NavTabs数组
    navTabs: sessionStorage.getItem('navTabs')
      ? JSON.parse(sessionStorage.getItem('navTabs'))
      : []
  },
  mutations: {
    // 控制侧边栏折叠状态改变
    AsideCollapse (state) {
      state.navCollapse = !state.navCollapse
    },
    // 将tab存入数组NavTabs中
    ADD_NAV_TAB (state, tab) {
      // 仪表盘(首页)页不需要添加，定义一个数组将其存在里面
      const noRequire = ['/home']
      // 判断是否已存在
      if ((state.navTabs.find(_tab => _tab.path === tab.path)) || noRequire.includes(tab.path)) {
        return false
      }
      state.navTabs.push(tab)
      persistNavTabs(state.navTabs)
    },

    // 点击删除Tab
    // 弹窗操作,点击关闭此tab
    DEL_TAB (state, index) {
      state.navTabs.splice(index, 1)
      // 如果已经全部删除完毕，则跳转 仪表盘页
      if (state.navTabs.length === 0) {
        router.replace('/home')
        return false
      }
      // 删除之后跳转到上一次记录
      router.replace(state.navTabs[state.navTabs.length - 1].path)
      persistNavTabs(state.navTabs)
    },

    // 弹窗操作
    // 点击关闭其他tab
    CLOSE_OTHER (state, index) {
      state.navTabs = state.navTabs.filter((tab, i) => i === index)
      router.replace(state.navTabs[0].path)
      persistNavTabs(state.navTabs)
    },
    // 点击关闭所有tab
    CLOSE_ALL (state) {
      state.navTabs = []
      router.replace('/home')
      persistNavTabs(state.navTabs)
    }

  }
}
